package com.bdqn.springcache.service;

import com.bdqn.springcache.dao.BookDao;
import com.bdqn.springcache.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    @Autowired
    private BookDao bookDao;

    //查找所有数
    public List<Book> findAllBooks() {
        return bookDao.findAll();
    }

    //将缓存的键定义为方法参数，值是方法的返回值
    @Cacheable(value = "book", key = "#id")
    //查找一本数
    public Book findBookById(int id) {
        System.out.println("从数据库中查找id为" + id + "的书，并添加到缓存，key为+" + id);
        return bookDao.findById(id).orElse(new Book());
    }

    //将缓存的键定义为参数book对象id属性，值为方法返回值
    @CachePut(value = "book", key = "#book.id")
    //添加一本书，同时添加到缓存
    public Book addBook(Book book) {
        System.out.println("将同一本书添加到数据库，同时添加到缓存");
        return bookDao.save(book);
    }

    //根据参数指定的键来删除缓存
    @CacheEvict(value = "book", key = "#id")
    public void deleteBook(int id) {
        System.out.println("从数据库删除一本书，同时删除key为" + id + "的缓存");
        bookDao.deleteById(id);
    }

    //修改缓存
    @CachePut(value = "book", key = "#book.id")
    //修改一本书
    public Book updateBook(Book book) {
        System.out.println("从数据库修改一本书，同时修改缓存，key为" + book.getId());
        return bookDao.save(book);
    }
}

